<template>
  <div class="session-list" :class="{ 'collapsed': collapsed }">
    <a-card title="会话列表" size="small" v-if="!collapsed">
      <template #extra>
        <a-button type="link" @click="createNewSession" :loading="creating">
          新建会话
        </a-button>
      </template>
      <a-list :data-source="chatStore.sessions || []" :loading="loading">
        <template #renderItem="{ item }: { item: Session }">
          <a-list-item 
            v-if="item"
            :class="{ 'active-session': item.id === chatStore.sessionId }"
            class="session-item"
          >
            <div class="session-content">
              <div class="session-info" @click="switchSession(item.id)">
                <div class="session-name" v-if="!editingSessionId || editingSessionId !== item.id">
                  {{ item.name }}
                </div>
                <a-input 
                  v-else
                  v-model:value="editingName"
                  @pressEnter="saveSessionName(item.id)"
                  size="small"
                  class="edit-input"
                  ref="editInput"
                  @click.stop
                />
                <div class="session-time">{{ formatTime(item.created_time) }}</div>
              </div>
              
              <div class="session-actions" @click.stop>
                <!-- 编辑状态下的按钮 -->
                <template v-if="editingSessionId === item.id">
                  <a-button 
                    type="primary" 
                    size="small"
                    @click="saveSessionName(item.id)"
                    class="action-btn"
                  >
                    保存
                  </a-button>
                  <a-button 
                    size="small"
                    @click="cancelEdit"
                    class="action-btn"
                  >
                    取消
                  </a-button>
                </template>
                
                <!-- 正常状态下的按钮 -->
                <template v-else>
                  <a-dropdown :trigger="['click']" placement="bottomRight">
                    <a-button type="text" size="small" class="more-btn">
                      <template #icon>
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                          <circle cx="12" cy="5" r="2"/>
                          <circle cx="12" cy="12" r="2"/>
                          <circle cx="12" cy="19" r="2"/>
                        </svg>
                      </template>
                    </a-button>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item @click="startEdit(item.id, item.name)">
                          <span>重命名</span>
                        </a-menu-item>
                        <a-menu-divider />
                        <a-menu-item 
                          @click="clearSession(item.id)"
                          :disabled="clearingSessionId === item.id"
                          danger
                        >
                          <span v-if="clearingSessionId === item.id">删除中...</span>
                          <span v-else>删除</span>
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </template>
              </div>
            </div>
          </a-list-item>
        </template>
      </a-list>
    </a-card>
    
    <!-- 收起状态下的简化显示 -->
    <div v-else class="collapsed-sessions">
      <div class="collapsed-header">
        <a-button type="text" @click="createNewSession" :loading="creating" size="small">
          <template #icon>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
            </svg>
          </template>
        </a-button>
      </div>
      <div class="collapsed-session-list">
        <template v-for="(session, index) in chatStore.sessions || []" :key="session?.id || index">
          <div 
            v-if="session"
            :class="['collapsed-session-item', { 'active': session.id === chatStore.sessionId }]"
            @click="switchSession(session.id)"
            :title="session.name"
          >
            <div class="session-indicator"></div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { useChatStore } from '@/stores/chat'
import { clearSession as clearSessionApi, updateSession } from '@/api/chat'

// 定义Session类型
interface Session {
  id: string
  name: string
  created_time: string
}

// 接收父组件传递的collapsed状态
defineProps<{
  collapsed?: boolean
}>()

const chatStore = useChatStore()
const loading = ref(false)
const creating = ref(false)
const clearingSessionId = ref<string | null>(null)
const editingSessionId = ref<string | null>(null)
const editingName = ref('')
const editInput = ref()

const startEdit = async (sessionId: string, currentName: string) => {
  editingSessionId.value = sessionId
  editingName.value = currentName
  await nextTick()
  if (editInput.value) {
    editInput.value.focus()
  }
}

const cancelEdit = () => {
  editingSessionId.value = null
  editingName.value = ''
}

const saveSessionName = async (sessionId: string) => {
  if (!editingName.value.trim()) {
    message.error('会话名称不能为空')
    return
  }
  
  try {
    await updateSession(sessionId, editingName.value.trim())
    await chatStore.loadSessions()
    message.success('会话名称已更新')
    cancelEdit()
  } catch (error) {
    message.error('更新会话名称失败')
    console.error('Update session name error:', error)
  }
}

const createNewSession = async () => {
  creating.value = true
  try {
    await chatStore.createNewSession()
    message.success('新会话创建成功')
  } catch (error) {
    message.error('创建会话失败')
  } finally {
    creating.value = false
  }
}

const switchSession = async (sessionId: string) => {
  if (sessionId === chatStore.sessionId) return
  
  loading.value = true
  try {
    chatStore.setSessionId(sessionId)
    await chatStore.loadSessionHistory()
    message.success('已切换会话')
  } catch (error) {
    message.error('切换会话失败')
  } finally {
    loading.value = false
  }
}

const clearSession = async (sessionId: string) => {
  clearingSessionId.value = sessionId
  try {
    await clearSessionApi(sessionId)
    
    // 如果删除的是当前会话，切换到其他会话
    if (sessionId === chatStore.sessionId) {
      const remainingSessions = chatStore.sessions.filter(s => s.id !== sessionId)
      if (remainingSessions.length > 0) {
        chatStore.setSessionId(remainingSessions[0].id)
        await chatStore.loadSessionHistory()
      } else {
        // 如果没有其他会话，创建新会话
        await chatStore.createNewSession()
      }
    }
    
    // 重新加载会话列表
    await chatStore.loadSessions()
    message.success('会话已删除')
  } catch (error) {
    message.error('删除会话失败')
  } finally {
    clearingSessionId.value = null
  }
}

const formatTime = (timeStr: string) => {
  if (!timeStr || timeStr === '未知时间') return '未知时间'
  try {
    const date = new Date(timeStr)
    return date.toLocaleString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch {
    return '未知时间'
  }
}

onMounted(async () => {
  loading.value = true
  try {
    await chatStore.initialize()
  } catch (error) {
    message.error('加载会话列表失败')
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.session-list {
  padding: 12px;
}

.session-list.collapsed {
  padding: 8px;
}

.session-item {
  cursor: pointer;
  transition: background-color 0.2s;
  padding: 8px 12px !important;
}

.session-item:hover {
  background-color: #fafafa;
}

.active-session {
  background-color: #f0f8ff;
  border-left: 3px solid #1890ff;
}

.session-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
  gap: 8px;
}

.session-info {
  flex: 1;
  min-width: 0; /* 允许文本截断 */
  cursor: pointer;
}

.session-name {
  font-weight: 500;
  margin-bottom: 4px;
  word-break: break-word;
  line-height: 1.4;
}

.session-time {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
}

.session-actions {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: 4px;
}

.edit-input {
  margin-bottom: 4px;
  width: calc(100% - 8px);
  min-width: 150px;
  min-height: 36px;
  padding: 8px 12px;
  font-size: 14px;
  line-height: 1.4;
  border-radius: 6px;
  border: 2px solid #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  background-color: #fff;
}

.edit-input:focus {
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(64, 169, 255, 0.3);
  outline: none;
}

.action-btn {
  min-width: 48px;
}

.more-btn {
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.more-btn:hover {
  background-color: #f5f5f5;
}

/* 收起状态下的样式 */
.collapsed-sessions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.collapsed-header {
  width: 100%;
  display: flex;
  justify-content: center;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.collapsed-session-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 100%;
  align-items: center;
}

.collapsed-session-item {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.collapsed-session-item:hover {
  background-color: #e6f7ff;
  transform: scale(1.1);
}

.collapsed-session-item.active {
  background-color: #1890ff;
}

.collapsed-session-item.active .session-indicator {
  background-color: white;
}

.session-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #999;
  transition: background-color 0.2s;
}

/* 确保在小屏幕上也能正常显示 */
@media (max-width: 768px) {
  .session-content {
    flex-direction: column;
    gap: 8px;
  }
  
  .session-actions {
    align-self: flex-end;
  }
}

/* 防止按钮溢出 */
.ant-list-item {
  overflow: hidden;
}
</style>